const qiniuUploader = require("./qiniuUploader");
import { configApp } from './config'
const FN = require('./public');
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

/*获取当前页url*/
function getCurrentPageUrl() {
  var pages = getCurrentPages()    //获取加载的页面
  var currentPage = pages[pages.length - 1]    //获取当前页面的对象
  var url = currentPage.route    //当前页面url
  return url
}

/*获取当前页带参数的url*/
function getCurrentPageUrlWithArgs() {
  var pages = getCurrentPages()    //获取加载的页面
  var currentPage = pages[pages.length - 1]    //获取当前页面的对象
  var url = currentPage.route    //当前页面url
  var options = currentPage.options    //如果要获取url中所带的参数可以查看options

  //拼接url的参数
  var urlWithArgs = url + '?'
  for (var key in options) {
    var value = options[key]
    urlWithArgs += key + '=' + value + '&'
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

  return urlWithArgs
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function getMaxNum(val) {
  var numArr = val.split(",");
  var max = Math.max.apply(null, numArr);
  return max;
}

function numberToFixed(value) {
  if (value) {
    return value.toFixed(0);
  }
  return 0;
}

// 获取用户头像
function hasAuto() {
  var userObj;
  wx.getSetting({
    success: function (res) {
      if (res.authSetting['scope.userInfo']) {
        wx.getUserInfo({
          success: function (res) {
            console.log(res);
            getApp().globalData.stuInfo = res.userInfo;
            return res.userInfo
          }
        })
      } else {
        return false;
      }
    },
    fail: function () {
      return false;
    }
  })
  //return userObj;
}

// 时间
function formatTimeTool(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();

  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();

  return [year, month, day].map(formatNumber);
}

// 比较时间戳是否超过31天 开始时间和结束时间
function dateDiff(str1, str2) {
  var first = str1 + '',
    second = str2 + '';
  var datadiff = str2 - str1;
  var time = 31 * 24 * 60 * 60 * 1000;
  if (first.length > 0 && second.length > 0) {
    if (datadiff < 0 || datadiff > time) {
      return false;
    }
    return true;
  }
  return false;
}

function getMaxPronAccuracy4free(Words) {
  const maxScore = Words.reduce((highest, word) => {
    return Math.max(highest, word.pron_accuracy).toFixed(1);
  }, 0);
  const errorWords = Words.reduce((errorArray, word) => {
    if (word.pron_accuracy < 90) {
      errorArray.push(word.word);
    }
    return errorArray;
  }, []);
  return { maxScore, errorWords };
}

function getMaxPronAccuracy4SOE(Words) {
  const maxScore = Words.reduce((highest, word) => {
    return Math.max(highest, word.PronAccuracy).toFixed(1);
  }, 0);
  const errorWords = Words.reduce((errorArray, word) => {
    if (word.PronAccuracy < 90) {
      errorArray.push(word.Word);
    }
    return errorArray;
  }, []);
  return { maxScore, errorWords };
}

// 将七牛云相关配置初始化进本sdk 
function initQiniu() {
  var options = {
    region: 'ECN',
    uptokenURL: configApp.api_base_url + 'qiniu/getUploadToken',
    domain: configApp.qiniuBucketURLPrefix,
    shouldUseQiniuFileName: true
  }
  qiniuUploader.init(options);
}

function qiniuUploaderUpload(filePath, fileName, callback4qiniuUpload) {
  // 向七牛云上传
  qiniuUploader.upload(filePath, (res) => {
    res.fileName = fileName;
    if (res.hasOwnProperty("error")) {
      FN.Toast('上传失败，请重新录制')
      util.initQiniu();
    } else {
      if (callback4qiniuUpload && typeof callback4qiniuUpload == 'function') {
        callback4qiniuUpload(res);
      }
    }
  }, (error) => {
    // console.error('error: ' + JSON.stringify(error));
  }, null, (progress) => {
  }, cancelTask => {

  }
  );
}
    module.exports = {
      dateDiff,
      hasAuto,
      formatTimeTool,
      getMaxNum,
      getCurrentPageUrl,
      getCurrentPageUrlWithArgs,
      getMaxPronAccuracy4SOE,
      getMaxPronAccuracy4free,
      initQiniu,
      qiniuUploaderUpload,
      formatTime, numberToFixed,    }